

#include <sys/socket.h>
#include <sys/file.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>


#include <stdio.h>
#include <sys/devpoll.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAXLINE 1500

void str_cli(FILE * fp, int sockfd){


    int sockfd = 0;
    char buffer[MAXLINE];

    int wfd = open("/dev/poll", O_RDWR, 0);


    struct pollfd pollfd[2];
    bzero(pollfd,sizeof(pollfd));

    pollfd[0].fd = fileno(fp);
    pollfd[0].events = POLLIN;
    pollfd[0].revents = 0;

    pollfd[1].fd = wfd;
    pollfd[1].events = POLLIN;
    pollfd[1].revents = 0;

    // pass pollfd data to wfd(/dev/poll))
    write(wfd, pollfd, sizeof(struct pollfd) * 2);

    int stdineof = 0;
    int n = 0;
    struct devpoll dopoll;
    bzero(&dopoll,sizeof(dopoll));
    for(; ; ){

	dopoll.dp_timeout = -1;// block
	dopoll.dp_nfds = 2;// number fds
	dopoll.dp_fds = pollfd;

	size_t result = Ioctl(wfd,DP_POLL,&dopoll);

	for(int i = 0; i < result; i++){

	    if(dopoll.dp_fds[i].fd == sockfd){

		if((n = read(sockfd, buffer, MAXLINE)) == 0){

		    if(stdineof == 1){

			return;
		    }else{


			printf("str_cli : server terminated perematurely");
			return;
		    }
		}
		write(fileno(stdout),buffer,n);
	    }else{

		if((n = read(fileno(fp), buffer, MAXLINE)) == 0){


		    stdineof = 1;
		    shutdown(sockfd, SHUT_WR);
		    continue;
		}
		write(sockfd, buffer, n);
	    }
	}
    }
}

